import { defineStore } from "pinia";
import { ref } from "vue";
import { getLoginUserUsingGet } from "@/api/userController";
import AccessEUM from "@/access/accessEUM";

/**
 * 登录用户信息全量获取
 */
export const useLoginUserStore = defineStore("loginUser", () => {
  const loginUser = ref<API.LoginUserVO>(getStoredUser());

  function setLoginUser(newLoginUser: API.LoginUserVO) {
    loginUser.value = newLoginUser;
    saveUserToLocalStorage(newLoginUser);
  }

  async function fetchLoginUser() {
    const res = await getLoginUserUsingGet();
    if (res.data.code === 0 && res.data.data) {
      console.log(res.data);
      loginUser.value = res.data.data;
      saveUserToLocalStorage(res.data.data);
    } else {
      loginUser.value = { userRole: AccessEUM.NOT_LOGIN };
      saveUserToLocalStorage(loginUser.value);
    }
  }

  function getStoredUser(): API.LoginUserVO {
    const storedUser = localStorage.getItem("loginUser");
    if (storedUser) {
      return JSON.parse(storedUser);
    }
    return { userName: "未登录" };
  }

  function saveUserToLocalStorage(user: API.LoginUserVO) {
    localStorage.setItem("loginUser", JSON.stringify(user));
  }

  return { loginUser, setLoginUser, fetchLoginUser };
});
